#!/usr/bin/env python
# -*- coding:utf-8 -*-

import nltk
import pylab

# 4.8 Python库
# 1. Matplotlib  绘图工具
# 支持matlab风格接口的复杂的绘图函数.
# 以图形的形式显示数值数据
# 显示按类别划分的布朗语料库中的特殊情态动词的频率.
# 布朗语料库中不同部分的情态动词频率.
"""
colors = 'rgbcmyk'
def bar_chart(categories,words,counts):
    "Plot a bar chart showing counts for each word by category"
    # import pylab 
    ind = pylab.arange(len(words))
    width = 1 / (len(categories) + 1)
    bar_groups = []
    for c in range(len(categories)):
        bars = pylab.bar(ind+c*width,counts[categories[c]],width,
     
        color=colors[c % len(colors)])

        bar_groups.append(bars)
    
    pylab.xticks(ind+width,words)
    pylab.legend([b[0] for b in bar_groups],categories,loc='upper left')
    pylab.ylabel('Frequency')
    pylab.title('Frequency of Six Modal Verbs by Genre')
    pylab.show()



genres = ['news','religion','hobbies','government','adventure']
modals = ['can','could','may','might','must','will']
cfdist = nltk.ConditionalFreqDist(
    (genre, word)
    for genre in genres
    for word in nltk.corpus.brown.words(categories=genre)  
    if word in modals)

counts = {}
for genre in genres:
    counts[genre] = [cfdist[genre][word] for word in modals]
bar_chart(genres,modals,counts)

# 条形图显示布朗语料库中不同部分的情态动词频率.
"""

"""
import matplotlib
matplotlib.use('Agg')
pylab.savefig('F:\\PythonProject\\AI\\NLP\\自然语言处理笔记\\images\\modals.png')
print('Content-Type: text/html')
print
print('<html><body>')
print('<img src="modals.png"/>')
print('</body></html>')
"""






# NetworkX
"""
NetworkX包定义和操作被称为图的由节点和边组成的结构.
NetworkX可以和Matplotlib结合使用可视化如WordNet的网络结构.

程序初始化一个空的图,然后遍历WordNet上位词层次为图添加边,遍历是递归的.
"""
"""
import networkx as nx 
import matplotlib
from nltk.corpus import wordnet as wn 

def traverse(graph,start,node):
    graph.depth[node.name] = node.shortest_path_distance(start)
    for child in node.hyponyms():
        graph.add_edge(node.name,child.name)
        traverse(graph,start,child)

def hyponym_graph(start):
    G = nx.Graph()
    G.depth = {}
    traverse(G,start,start)
    return G 

def graph_draw(graph):
    nx.draw_kamada_kawai(graph,
        node_size = [16 * graph.degree(n) for n in graph],
        node_color = [graph.depth[n] for n in graph],
        with_labels = False)
    matplotlib.pyplot.show()

dog = wn.synset('dog.n.01')
graph = hyponym_graph(dog)
graph_draw(graph)
"""







# NumPy
"""
NumPy(基本的数值运算包)对数值处理提供支持.
NumPy有一个多维数组对象,它可以很容易初始化和访问.
"""
"""
from numpy import array

cube = array([ [[0,0,0],[1,1,1],[2,2,2]],
        [[3,3,3],[4,4,4],[5,5,5]],
        [[6,6,6],[7,7,7],[8,8,8]] ])
print(cube[1,1,1])        
print(cube[2].transpose())
print(cube[2,1:])
"""



# NumPy包括线性代数函数,潜在语义分析能识别一个文档集合中的隐含概念.
from numpy import linalg
from numpy import array

a = array([[4,0],[3,-5]])
u,s,vt = linalg.svd(a)
print(u)
print(s)
print(vt)
"""
NLTK中的聚类包nltk.cluster中广泛使用NumPy数组,支持包括k-means聚类,
高斯EM聚类,组平均凝聚聚类以及聚类分析图.
"""